package com.tange.ai.core.sample.message

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.*
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.tange.ai.core.sample.R
import com.tange.ai.core.sample.databinding.ActivityMessageDetailBinding
import com.tange.base.toolkit.*
import com.tange.core.cloud.message.CloudMessage
import com.tange.core.cloud.message.Message
import com.tange.core.media.render.DeviceMediaRender
import com.tange.core.media.source.impl.cloud.CloudStorageMediaSource

class MessageDetailActivity : AppCompatActivity() {

    companion object {
        private const val TAG = "MessageDetailActivity_"
        private const val PARAM_MESSAGE_ID = "PARAM_MESSAGE_ID"
        private const val PARAM_DEVICE_ID = "PARAM_DEVICE_ID"

        fun launch(context: Context, deviceId: String, messageId: String) {
            context.startActivity(Intent(context, MessageDetailActivity::class.java).apply {
                putExtra(PARAM_DEVICE_ID, deviceId)
                putExtra(PARAM_MESSAGE_ID, messageId)
            })
        }
    }

    private lateinit var binding: ActivityMessageDetailBinding
    private lateinit var messageId: String
    private lateinit var deviceId: String


    private var containsVideo = false
    private lateinit var deviceMediaRender: DeviceMediaRender
    private lateinit var cloudStorageMediaSource: CloudStorageMediaSource

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        StatusBarUtil.setLightStatusBar(this, true)
        StatusNavUtils.setStatusBarColor(this, ContextCompat.getColor(this, R.color.app_background))
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        messageId = intent.getStringExtra(PARAM_MESSAGE_ID)
        deviceId = intent.getStringExtra(PARAM_DEVICE_ID)

        binding = ActivityMessageDetailBinding.inflate(layoutInflater).apply {
            setContentView(root)
            supportActionBar?.hide()
            root.paddingStatusBar()
            top.left.onClicked { finish() }
        }

        initRender()

        CloudMessage.queryMessageById(messageId) {
            if (it.success) it.data?.let { refresh(it) }
            else Tips.show("请求消息失败： ${it.code}, ${it.message}")
        }
    }

    private fun refresh(message: Message) {

        binding.cover.visible()
        message.image?.let {
            Glide.with(this@MessageDetailActivity)
                .load(it)
                .error(R.drawable.light_gray_rounded_bg)
                .into(binding.cover)
        }

        message.event?.categoryName?.let { binding.msgCategoryName.text = it }
        message.event?.categoryLabel?.let { binding.msgCategoryLabel.text = it }
        message.event?.msg?.let { binding.msgDetail.text = it }
        message.startTime?.let { binding.msgTime.text = DateUtil.getStrToTime(it) }

        if (message.containsVideo == true) {
            containsVideo = true
            binding.play.visible()
            binding.play.onClicked {
                binding.loading.visible()
                binding.play.gone()

                // 提交任务，开始下载数据
                cloudStorageMediaSource.setDataSource(message.toDataSource())
                cloudStorageMediaSource.seek(message.startTime ?: 0)
            }
        } else {
            binding.play.gone()
        }

    }

    private fun initRender() {

        cloudStorageMediaSource = CloudStorageMediaSource(this, deviceId).apply {
            enableVideoProduce(true)
            enableAudioProduce(true)
        }

        // 创建媒体播放器
        deviceMediaRender = DeviceMediaRender(this, cloudStorageMediaSource).apply {

            // 将播放器示例绑定到UI上
            attach(binding.playerContainer, createCenterLayoutParams())

            // 监听首帧数据渲染回调
            observeFirstFrameRendered {
                binding.loading.gone()
                binding.cover.gone()
            }
        }
    }

    override fun onResume() {
        super.onResume()
        if (containsVideo) {
            deviceMediaRender.enableVideoRender(true)
            cloudStorageMediaSource.enableVideoProduce(true)
            cloudStorageMediaSource.enableAudioProduce(true)
            binding.play.visible()
            binding.loading.gone()
            binding.cover.visible()
        }
    }

    override fun onPause() {
        super.onPause()
        if (containsVideo) {
            deviceMediaRender.enableAudioRender(false)
            cloudStorageMediaSource.enableVideoProduce(false)
            cloudStorageMediaSource.enableAudioProduce(false)
        }
    }

    private fun createCenterLayoutParams() = FrameLayout.LayoutParams(
        FrameLayout.LayoutParams.MATCH_PARENT,
        FrameLayout.LayoutParams.MATCH_PARENT
    ).apply { gravity = Gravity.CENTER }
}